package com.ddiviewer;

//=============================================================================
// Imports
//=============================================================================
import android.util.Log;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.*;
import java.util.List;
import java.util.Vector;

//=============================================================================
// SearchTab
//=============================================================================
public class SearchTab extends ListActivity {


    //=========================================================================
    // Variables
    //=========================================================================
	String 						baseUrl			= null;
	String 						nameonly		= null;
	String 						loginUrl		= null;
	String 						searchUrl		= null;
	String 						prefFileName	= null;
	String						results			= null;
	
	String[]					tabs			= null;

	View 						v				= null;
	Button 						search	 		= null;
	CheckBox					checkbox		= null;
	EditText					keyword			= null;
	CheckBox 					checkBox		= null;	
	ProgressDialog 				pd				= null;
	InputMethodManager			keyboard		= null;
	
	static Item 				save			= null;
	static List<Item>			item			= null;
	static List<Item>			favorite		= null;
	static ItemAdapter			itemAdapter		= null;
	
	private static final int FAVORITE_ADD		= 0;
	private static final int FAVORITE_CANCEL	= 1;


    //=========================================================================
    // Constructor
    //=========================================================================
	public SearchTab() { 
		item		= new Vector<Item>();					// Set up Item list
		favorite	= new Vector<Item>();
	}


    //=========================================================================
    // onCreate()
	// Contains adapters, Context menu info, Content
    //=========================================================================
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        itemAdapter = new ItemAdapter(this, R.layout.list, (Vector<Item>) item);
        setListAdapter(itemAdapter);
        setContentView(R.layout.search);

        // Set up the cookie manager, needed for Web View
        CookieSyncManager.createInstance(this);
        CookieManager.getInstance().removeAllCookie();
        
        // Set up Views
        search			= (Button) findViewById(R.id.submit);
        keyword			= (EditText) findViewById(R.id.keyword);
        checkBox		= (CheckBox) findViewById(R.id.checkBox);
        keyboard		= (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        tabs 			= getResources().getStringArray(R.array.tabs);
        baseUrl			= getResources().getString(R.string.baseUrl);
        loginUrl		= getResources().getString(R.string.loginUrl);
        searchUrl		= getResources().getString(R.string.searchUrl);
        prefFileName	= getResources().getString(R.string.prefFileName);

        // onClickListener for EditText box
        keyword.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        		keyboard.hideSoftInputFromWindow(keyword.getWindowToken(), 1);
        	}
        });

        // onKeyListener for EditText box
        keyword.setOnKeyListener(new View.OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER) {
					search.requestFocus();
					search.dispatchKeyEvent(event);
					return true;
				}
				return false;
			}
        });

        // onClickListener for Search button
        search.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				itemAdapter.notifyDataSetInvalidated();
				((Vector<Item>) item).removeAllElements();
				pd = ProgressDialog.show(SearchTab.this, "Working...", "Retrieving Data - Please Wait.", true, false);
				if (checkBox.isChecked()) nameonly = "true"; else nameonly = "false";
				keyboard.hideSoftInputFromWindow(keyword.getWindowToken(), 0);
				MainThread mt = new MainThread(v, handler, searchUrl, keyword.getText().toString(), nameonly);
				mt.start();				
			}
		});

        registerForContextMenu(getListView());
    }


    //=========================================================================
    // onCreateContextMenu()
	// Set up a Web View when we choose a List Item
    //=========================================================================
    @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	super.onCreateContextMenu(menu, v, menuInfo);
    	menu.setHeaderTitle("Test");
    	menu.add(0, FAVORITE_ADD, 0, "Add to Favorites");
    	menu.add(0, FAVORITE_CANCEL, 0, "Cancel");
    }
    
    
    //=========================================================================
    // onContextItemSelected()
	// Set up a Web View when we choose a List Item
    //=========================================================================
    @Override public boolean onContextItemSelected(MenuItem item) {
    	AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    	
    	switch(item.getItemId()) {
    		case FAVORITE_ADD:
    			favorite.add((Item) getListView().getAdapter().getItem(menuInfo.position));
    			return true;
    		case FAVORITE_CANCEL:
    			return true;
    	}
    	return true;
    
    }

    
    //=========================================================================
    // onListItemClick()
	// Set up a Web View when we choose a List Item
    //=========================================================================
	@Override public void onListItemClick(ListView parent, View v, int position, long id) {
		SharedPreferences sp = getSharedPreferences(prefFileName, MODE_PRIVATE);
        
        if (sp.getString("username", null) == null || sp.getString("password", null) == null) {
        	startDialog();
        } else {
        	save = new Item();
        	save = (Item) getListAdapter().getItem(position);
        	Intent in = new Intent(this, DDIWebView.class);
        	startActivity(in);
        }
	}
	
	
    //=========================================================================
    // onKeyUp()
    //=========================================================================
	@Override public boolean onKeyUp(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_MENU)) {
			startDialog();
			return true;
		}
		return false;
	}
	
	
    //=========================================================================
    // startDialog()
    //=========================================================================
	public void startDialog() {
		Intent in = new Intent(this, AuthenticationDialog.class);
		startActivity(in);
	}


    //=========================================================================
    // onSaveInstanceState()
    //=========================================================================
    @Override public void onSaveInstanceState(Bundle savedInstanceState) {
    	super.onSaveInstanceState(savedInstanceState);
    	
    	savedInstanceState.putString("keyword", keyword.getText().toString());
    	savedInstanceState.putBoolean("checkBox", (checkBox.isChecked() ? true : false));
    	itemAdapter.notifyDataSetInvalidated();
    	CookieSyncManager.getInstance().startSync();
    }
   
    
    //=========================================================================
    // onRestoreInstanceState()
    //=========================================================================
    @Override public void onRestoreInstanceState(Bundle savedInstanceState) {
    	super.onRestoreInstanceState(savedInstanceState);
    	
    	keyword.setText(savedInstanceState.getString("keyword"));
    	checkBox.setChecked(savedInstanceState.getBoolean("checkBox"));
    	itemAdapter.notifyDataSetInvalidated();
    	CookieSyncManager.getInstance();
    }

    
    //=========================================================================
    // new Handler()
    //=========================================================================
    private Handler handler = new Handler() {    	
    	@Override
    	public void handleMessage(Message msg) {
    		switch(msg.what) {
    			case 0:
    				super.handleMessage(msg);
    				break;
    			case 1:
    				super.handleMessage(msg);
    				pd.dismiss();
    				break;
    			default:
    				Log.e("DDIViewer", "Invalid Message");
    				break;
    		}
    		
    		itemAdapter.notifyDataSetChanged();
    	}
    };


}